<?php

/*
 * @see https://leetcode.cn/problems/longest-substring-without-repeating-characters/
 */

class Solution
{
    public function base(array $input): int
    {
        $result = 0;
        $length = count($input);
        $currentLength = 0;

        for ($i = 0; $i < $length; $i++) {
            $position = $i - $currentLength;
            $isRepeat = false;
            for ($j = $i - 1; $j >= $position; $j--) {
                if ($input[$i] === $input[$j]) {
                    $result = max($currentLength, $result);
                    $currentLength = $i - $j;
                    $isRepeat = true;
                }
            }

            if (!$isRepeat) $currentLength++;
        }

        return max($currentLength, $result);
    }

    public function handle(array $input): int
    {
        $result = 0;
        $length = count($input);
        $hashMap = [];
        $left = 0;

        for ($i = 0; $i < $length; $i++) {
            if (isset($hashMap[$input[$i]])) {
                $left = max($left, $hashMap[$input[$i]] + 1);
            }

            if ($left + $result >= $length) {
                break;
            }

            $hashMap[$input[$i]] = $i;

            $result = max($result, $i - $left + 1);
        }

        return $result;
    }
}

// cdd 2
// abcabcbb 3
var_dump((new Solution())->handle(array_filter(str_split('cdd'))));


